<?php
session_start();
require_once 'common/config.php';
require_once 'common/db.php';

// 启用错误显示
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// 检查用户是否登录且为考试项目管理员
if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== '考试项目管理员') {
    header('Location: login.php');
    exit();
}

// 获取考试项目ID
if (!isset($_GET['exam_id'])) {
    echo "<script>alert('缺少考试项目ID'); window.location.href='exam_projects.php';</script>";
    exit();
}

$exam_id = $_GET['exam_id'];

// 连接数据库
$conn = getDBConnection();

// 获取考试项目信息
$stmt = $conn->prepare("SELECT exam_name FROM exams WHERE exam_id = ?");
$stmt->bind_param("s", $exam_id);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    echo "<script>alert('考试项目不存在'); window.location.href='exam_projects.php';</script>";
    exit();
}

$exam = $result->fetch_assoc();
$exam_name = $exam['exam_name'];

// 处理AJAX请求
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    header('Content-Type: application/json');
    
    $action = $_POST['action'] ?? '';
    
    if ($action === 'generate_room_numbers') {
        try {
            $session_id = $_POST['session_id'] ?? '';
            
            // 获取场次数据
            $stmt = $conn->prepare("SELECT * FROM arrange_examination_rooms_and_invigilators WHERE exam_id = ? AND session_number = ?");
            $stmt->bind_param("si", $exam_id, $session_id);
            $stmt->execute();
            $result = $stmt->get_result();
            
            if ($result->num_rows === 0) {
                echo json_encode(['success' => false, 'error' => '找不到场次数据']);
                exit();
            }
            
            $session = $result->fetch_assoc();
            $required_rooms = (int)$session['required_rooms'];
            $backup_rooms = (int)$session['backup_rooms'];
            $room_type = $session['room_type'];
            $numbering_rule = $session['numbering_rule'];
            
            // 根据编号规律生成考场号
            $room_numbers = [];
            
            switch ($numbering_rule) {
                case '类型1:第X考场':
                    for ($i = 1; $i <= $required_rooms; $i++) {
                        $room_numbers[] = '第' . $i . '考场';
                    }
                    if ($backup_rooms > 0) {
                        $room_numbers[] = '备用考场';
                    }
                    break;
                    
                case '类型2:XX考场':
                    for ($i = 1; $i <= $required_rooms; $i++) {
                        $room_numbers[] = sprintf('%02d', $i) . '考场';
                    }
                    if ($backup_rooms > 0) {
                        $room_numbers[] = '备用考场';
                    }
                    break;
                    
                case '类型3:0XX考场':
                    for ($i = 1; $i <= $required_rooms; $i++) {
                        $room_numbers[] = sprintf('%03d', $i) . '考场';
                    }
                    if ($backup_rooms > 0) {
                        $room_numbers[] = '备用考场';
                    }
                    break;
                    
                case '类型4:1XX考场':
                    for ($i = 1; $i <= $required_rooms; $i++) {
                        $room_numbers[] = '1' . sprintf('%02d', $i) . '考场';
                    }
                    if ($backup_rooms > 0) {
                        $room_numbers[] = '备用考场';
                    }
                    break;
                    
                case '类型5:4460010XX考场':
                    for ($i = 1; $i <= $required_rooms; $i++) {
                        $room_numbers[] = '446001' . sprintf('%03d', $i) . '考场';
                    }
                    if ($backup_rooms > 0) {
                        $room_numbers[] = '备用考场';
                    }
                    break;
                    
                default:
                    echo json_encode(['success' => false, 'error' => '未知的编号规律']);
                    exit();
            }
            
            echo json_encode([
                'success' => true,
                'room_numbers' => $room_numbers,
                'required_count' => $required_rooms,
                'backup_count' => $backup_rooms,
                'total_count' => count($room_numbers)
            ]);
            exit();
            
        } catch (Exception $e) {
            echo json_encode(['success' => false, 'error' => $e->getMessage()]);
            exit();
        }
    }
    
    if ($action === 'save_room_numbers') {
        try {
            $session_id = $_POST['session_id'] ?? '';
            $room_numbers = json_decode($_POST['room_numbers'] ?? '[]', true);
            
            if (empty($room_numbers)) {
                echo json_encode(['success' => false, 'error' => '考场号列表不能为空']);
                exit();
            }
            
            // 保存考场号列表
            $room_numbers_json = json_encode($room_numbers, JSON_UNESCAPED_UNICODE);
            
            $stmt = $conn->prepare("UPDATE arrange_examination_rooms_and_invigilators SET exam_room_numbers = ? WHERE exam_id = ? AND session_number = ?");
            $stmt->bind_param("ssi", $room_numbers_json, $exam_id, $session_id);
            
            if ($stmt->execute()) {
                echo json_encode(['success' => true, 'message' => '考场号已保存']);
            } else {
                echo json_encode(['success' => false, 'error' => '保存失败']);
            }
            exit();
            
        } catch (Exception $e) {
            echo json_encode(['success' => false, 'error' => $e->getMessage()]);
            exit();
        }
    }
}

// 获取现有数据
$stmt = $conn->prepare("SELECT * FROM arrange_examination_rooms_and_invigilators WHERE exam_id = ? ORDER BY session_number");
$stmt->bind_param("s", $exam_id);
$stmt->execute();
$result = $stmt->get_result();
$existing_data = $result->fetch_all(MYSQLI_ASSOC);

$conn->close();
?>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>编排考场号 - 考试管理系统</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        .milestone-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 2rem 0;
            margin-bottom: 2rem;
        }
        
        .room-number-item {
            background: #f8f9fa;
            border: 1px solid #dee2e6;
            border-radius: 0.5rem;
            padding: 1rem;
            margin: 0.5rem;
            text-align: center;
            font-weight: bold;
            color: #495057;
        }
        
        .room-number-item.backup {
            background: #fff3cd;
            border-color: #ffeaa7;
            color: #856404;
        }
        
        .room-numbers-display {
            display: flex;
            flex-wrap: wrap;
            justify-content: center;
            align-items: center;
        }
        
        .numbering-preview {
            background: #e7f3ff;
            border: 1px solid #b3d7ff;
            border-radius: 0.5rem;
            padding: 1rem;
            margin: 1rem 0;
        }
        
        .session-card {
            border: 1px solid #dee2e6;
            border-radius: 0.5rem;
            margin-bottom: 1rem;
        }
        
        .session-header {
            background: #f8f9fa;
            border-bottom: 1px solid #dee2e6;
            padding: 1rem;
            font-weight: bold;
        }
        
        .session-content {
            padding: 1rem;
        }
    </style>
</head>
<body>
    <?php include_once 'common/navigation.php'; ?>
    
    <div class="milestone-header">
        <div class="container">
            <h2 class="mb-0">编排考场号</h2>
            <p class="mb-0">里程碑4：为各考试场次生成规范的考场编号</p>
        </div>
    </div>
    
    <div class="container">
        <div class="row mb-4">
            <div class="col-12">
                <div class="card">
                    <div class="card-header">
                        <h5 class="mb-0">考试项目信息</h5>
                    </div>
                    <div class="card-body">
                        <p><strong>考试项目名称：</strong><?php echo htmlspecialchars($exam_name); ?></p>
                        <p><strong>项目ID：</strong><?php echo htmlspecialchars($exam_id); ?></p>
                    </div>
                </div>
            </div>
        </div>
        
        <?php if (empty($existing_data)): ?>
            <div class="alert alert-warning" role="alert">
                <h5>暂无考场数据</h5>
                <p>请先完成前面的里程碑步骤，填写考场信息后再进行考场号编排。</p>
                <a href="arrange_examination_rooms_milestone1.php?exam_id=<?php echo $exam_id; ?>" class="btn btn-primary">返回里程碑1</a>
            </div>
        <?php else: ?>
            <div class="row">
                <div class="col-12">
                    <div class="card">
                        <div class="card-header">
                            <h5>考场号编排</h5>
                        </div>
                        <div class="card-body">
                            <p class="text-muted mb-4">根据各场次的编号规律生成标准化考场号。点击"生成考场号"按钮为每个场次生成相应的考场编号。</p>
                            
                            <?php foreach ($existing_data as $session): ?>
                                <div class="session-card">
                                    <div class="session-header">
                                        第<?php echo $session['session_number']; ?>场次 - <?php echo htmlspecialchars($session['subject_name']); ?>
                                    </div>
                                    <div class="session-content">
                                        <div class="row">
                                            <div class="col-md-6">
                                                <h6>场次信息</h6>
                                                <ul class="list-unstyled">
                                                    <li><strong>考试日期：</strong><?php echo $session['exam_date']; ?></li>
                                                    <li><strong>考试时间：</strong><?php echo $session['start_time']; ?> - <?php echo $session['end_time']; ?></li>
                                                    <li><strong>考场类型：</strong><?php echo $session['room_type']; ?></li>
                                                    <li><strong>需要考场：</strong><?php echo $session['required_rooms']; ?>个（不含备用）</li>
                                                    <li><strong>备用考场：</strong><?php echo $session['backup_rooms']; ?>个</li>
                                                    <li><strong>编号规律：</strong><?php echo $session['numbering_rule']; ?></li>
                                                </ul>
                                            </div>
                                            <div class="col-md-6">
                                                <h6>考场号生成</h6>
                                                <button class="btn btn-success mb-3" onclick="generateRoomNumbers(<?php echo $session['session_number']; ?>)">
                                                    生成考场号
                                                </button>
                                                
                                                <div id="room-numbers-result-<?php echo $session['session_number']; ?>" class="numbering-preview" style="display: none;">
                                                    <h6>生成的考场号：</h6>
                                                    <div id="room-numbers-display-<?php echo $session['session_number']; ?>" class="room-numbers-display">
                                                        <!-- 考场号将在这里显示 -->
                                                    </div>
                                                    <div class="mt-3">
                                                        <button class="btn btn-primary btn-sm" onclick="saveRoomNumbers(<?php echo $session['session_number']; ?>)">
                                                            保存考场号
                                                        </button>
                                                        <button class="btn btn-secondary btn-sm" onclick="editRoomNumbers(<?php echo $session['session_number']; ?>)">
                                                            手动编辑
                                                        </button>
                                                    </div>
                                                </div>
                                                
                                                <?php if (!empty($session['exam_room_numbers'])): ?>
                                                    <div class="alert alert-success">
                                                        <h6>已保存的考场号：</h6>
                                                        <div class="room-numbers-display">
                                                            <?php 
                                                            $saved_numbers = json_decode($session['exam_room_numbers'], true);
                                                            if ($saved_numbers) {
                                                                foreach ($saved_numbers as $number) {
                                                                    $class = (strpos($number, '备用') !== false) ? 'backup' : '';
                                                                    echo '<div class="room-number-item ' . $class . '">' . htmlspecialchars($number) . '</div>';
                                                                }
                                                            }
                                                            ?>
                                                        </div>
                                                    </div>
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                            
                            <div class="row mt-4">
                                <div class="col-12 text-center">
                                    <a href="arrange_examination_rooms_milestone3.php?exam_id=<?php echo $exam_id; ?>" class="btn btn-secondary me-2">
                                        ← 返回里程碑3
                                    </a>
                                    <a href="arrange_examination_rooms_milestone5.php?exam_id=<?php echo $exam_id; ?>" class="btn btn-primary">
                                        下一步：里程碑5 →
                                    </a>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        <?php endif; ?>
    </div>
    
    <!-- 手动编辑考场号模态框 -->
    <div class="modal fade" id="editRoomNumbersModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">手动编辑考场号</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">考场号列表（每行一个）：</label>
                        <textarea id="manualRoomNumbers" class="form-control" rows="10" placeholder="请输入考场号，每行一个"></textarea>
                        <div class="form-text">请按顺序输入考场号，备用考场请使用"备用考场"</div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" onclick="applyManualRoomNumbers()">应用</button>
                </div>
            </div>
        </div>
    </div>
    
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        let currentEditingSession = null;
        let currentRoomNumbers = [];
        
        function generateRoomNumbers(sessionId) {
            $.ajax({
                url: '',
                type: 'POST',
                data: {
                    action: 'generate_room_numbers',
                    session_id: sessionId
                },
                dataType: 'json',
                success: function(response) {
                    if (response.success) {
                        displayRoomNumbers(sessionId, response.room_numbers);
                        $('#room-numbers-result-' + sessionId).show();
                    } else {
                        alert('生成考场号失败：' + response.error);
                    }
                },
                error: function() {
                    alert('请求失败，请重试');
                }
            });
        }
        
        function displayRoomNumbers(sessionId, roomNumbers) {
            const container = $('#room-numbers-display-' + sessionId);
            container.empty();
            
            roomNumbers.forEach(function(number) {
                const isBackup = number.includes('备用');
                const itemClass = isBackup ? 'room-number-item backup' : 'room-number-item';
                container.append('<div class="' + itemClass + '">' + number + '</div>');
            });
            
            // 存储当前考场号以便保存
            currentRoomNumbers = roomNumbers;
            currentEditingSession = sessionId;
        }
        
        function saveRoomNumbers(sessionId) {
            if (!currentRoomNumbers || currentRoomNumbers.length === 0) {
                alert('没有可保存的考场号');
                return;
            }
            
            $.ajax({
                url: '',
                type: 'POST',
                data: {
                    action: 'save_room_numbers',
                    session_id: sessionId,
                    room_numbers: JSON.stringify(currentRoomNumbers)
                },
                dataType: 'json',
                success: function(response) {
                    if (response.success) {
                        alert('考场号保存成功！');
                        location.reload();
                    } else {
                        alert('保存失败：' + response.error);
                    }
                },
                error: function() {
                    alert('保存请求失败，请重试');
                }
            });
        }
        
        function editRoomNumbers(sessionId) {
            currentEditingSession = sessionId;
            
            // 将当前考场号填入编辑框
            if (currentRoomNumbers && currentRoomNumbers.length > 0) {
                $('#manualRoomNumbers').val(currentRoomNumbers.join('\n'));
            }
            
            // 显示模态框
            new bootstrap.Modal(document.getElementById('editRoomNumbersModal')).show();
        }
        
        function applyManualRoomNumbers() {
            const manualNumbers = $('#manualRoomNumbers').val().trim();
            if (!manualNumbers) {
                alert('请输入考场号');
                return;
            }
            
            const roomNumbers = manualNumbers.split('\n')
                .map(num => num.trim())
                .filter(num => num.length > 0);
            
            if (roomNumbers.length === 0) {
                alert('请输入有效的考场号');
                return;
            }
            
            // 更新显示
            displayRoomNumbers(currentEditingSession, roomNumbers);
            
            // 关闭模态框
            bootstrap.Modal.getInstance(document.getElementById('editRoomNumbersModal')).hide();
        }
    </script>
    
    <!-- 引入jQuery -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</body>
</html>